import tracker from '../utils/tracker'
import getLastEvent from '../utils/getLastEvent'
import getSelector from '../utils/getSelector'
// 响应用户交互的响应时间如果大于100ms,用户就会感觉卡顿
export function longTask(){
  new PerformanceObserver((list)=>{
    list.getEntries().forEach(entry=>{
      if(entry.duration > 100){
        const lastEvnet = getLastEvent()
        // 浏览器空闲时执行，在下一次事件循环之前
        window.requestIdleCallback(()=>{
          tracker.send({
            kind:"experience",
            type:"longTask",
            eventType:lastEvnet.type,
            startTime:fromTime(entry.startTime),
            duration:fromTime(entry.duration),
            selector:lastEvnet ? getSelector(lastEvnet.path || lastEvnet.target) : ''
          })
        })
      }
    })
  }).observe({entryTypes:['longtask']})
}

function fromTime(time){
  return `${time}`.split(".")[0]
}